<template>
  <aside class="app-sidebar" :class="{ 'mobile-open': mobileOpen }">
    <!-- Logo -->
    <div class="sidebar-logo">
      <h1 class="sidebar-logo-text">
        {{ logoText }}
      </h1>
    </div>

    <!-- 导航菜单 -->
    <nav class="sidebar-nav">
      <div class="sidebar-nav-container">
        <div class="sidebar-menu">
          <!-- 模型管理 -->
          <div class="sidebar-menu-item">
            <button @click="toggleMenu('modelManagement')" class="sidebar-menu-btn"
              :class="{ 'active': activeMenu === 'modelManagement' }">
              <div class="sidebar-menu-btn-content">
                <i class="ri-cube-line sidebar-menu-btn-icon"></i>
                <span class="sidebar-menu-btn-text">模型管理</span>
              </div>
              <i class="sidebar-menu-btn-arrow"
                :class="menuExpanded.modelManagement ? 'ri-arrow-down-s-line expanded' : 'ri-arrow-up-s-line'">
              </i>
            </button>

            <!-- 子菜单 -->
            <transition name="submenu">
              <div v-if="menuExpanded.modelManagement" class="sidebar-submenu">
                <a href="#" @click.prevent="selectSubMenu('modelManagement', 'modelLifecycle')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('modelManagement', 'modelLifecycle') }">
                  模型生命周期
                </a>
                <a href="#" @click.prevent="selectSubMenu('modelManagement', 'modelPerformance')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('modelManagement', 'modelPerformance') }">
                  模型性能评估
                </a>
                <a href="#" @click.prevent="selectSubMenu('modelManagement', 'modelConversion')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('modelManagement', 'modelConversion') }">
                  模型转换适配
                </a>
              </div>
            </transition>
          </div>

          <!-- 推理服务 -->
          <div class="sidebar-menu-item">
            <button @click="toggleMenu('inference')" class="sidebar-menu-btn"
              :class="{ 'active': activeMenu === 'inference' }">
              <div class="sidebar-menu-btn-content">
                <i class="ri-rocket-line sidebar-menu-btn-icon"></i>
                <span class="sidebar-menu-btn-text">推理服务</span>
              </div>
              <i class="sidebar-menu-btn-arrow"
                :class="menuExpanded.inference ? 'ri-arrow-down-s-line expanded' : 'ri-arrow-up-s-line'">
              </i>
            </button>

            <!-- 子菜单 -->
            <transition name="submenu">
              <div v-if="menuExpanded.inference" class="sidebar-submenu">
                <a href="#" @click.prevent="selectSubMenu('inference', 'inferenceHome')" class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('inference', 'inferenceHome') }">
                  首页
                </a>
                <a href="#" @click.prevent="selectSubMenu('inference', 'createInference')" class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('inference', 'createInference') }">
                  创建推理服务
                </a>
                <a href="#" @click.prevent="selectSubMenu('inference', 'pipelineBuild')" class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('inference', 'pipelineBuild') }">
                  流水线构建
                </a>
                <a href="#" @click.prevent="selectSubMenu('inference', 'batchInference')" class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('inference', 'batchInference') }">
                  批量推理任务
                </a>
                <a href="#" @click.prevent="selectSubMenu('inference', 'inferenceOptimization')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('inference', 'inferenceOptimization') }">
                  推理加速优化
                </a>
              </div>
            </transition>
          </div>

          <!-- API 接口 -->
          <div class="sidebar-menu-item">
            <button @click="selectMenu('api')" class="sidebar-menu-btn" :class="{ 'active': activeMenu === 'api' }">
              <div class="sidebar-menu-btn-content">
                <i class="ri-code-box-line sidebar-menu-btn-icon"></i>
                <span class="sidebar-menu-btn-text">API 接口</span>
              </div>
            </button>
          </div>

          <!-- 数据处理 -->
          <div class="sidebar-menu-item">
            <button @click="toggleMenu('dataProcessing')" class="sidebar-menu-btn"
              :class="{ 'active': activeMenu === 'dataProcessing' }">
              <div class="sidebar-menu-btn-content">
                <i class="ri-database-2-line sidebar-menu-btn-icon"></i>
                <span class="sidebar-menu-btn-text">数据处理</span>
              </div>
              <i class="sidebar-menu-btn-arrow"
                :class="menuExpanded.dataProcessing ? 'ri-arrow-down-s-line expanded' : 'ri-arrow-up-s-line'">
              </i>
            </button>

            <!-- 子菜单 -->
            <transition name="submenu">
              <div v-if="menuExpanded.dataProcessing" class="sidebar-submenu">
                <a href="#" @click.prevent="selectSubMenu('dataProcessing', 'dataTemplate')"
                  class="sidebar-submenu-link" :class="{ 'active': isActiveSubMenu('dataProcessing', 'dataTemplate') }">
                  数据处理页模板
                </a>
                <a href="#" @click.prevent="selectSubMenu('dataProcessing', 'dataPreprocess')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('dataProcessing', 'dataPreprocess') }">
                  数据预处理
                </a>
                <a href="#" @click.prevent="selectSubMenu('dataProcessing', 'dataAugmentation')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('dataProcessing', 'dataAugmentation') }">
                  数据增强
                </a>
                <a href="#" @click.prevent="selectSubMenu('dataProcessing', 'processedResults')"
                  class="sidebar-submenu-link"
                  :class="{ 'active': isActiveSubMenu('dataProcessing', 'processedResults') }">
                  处理后结果
                </a>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </nav>
  </aside>
</template>

<script>
export default {
  name: 'Sidebar',
  props: {
    // Logo 文字
    logoText: {
      type: String,
      default: 'logo'
    },
    // 默认激活的主菜单
    defaultActiveMenu: {
      type: String,
      default: 'modelManagement'
    },
    // 默认激活的子菜单
    defaultActiveSubMenu: {
      type: String,
      default: 'modelLifecycle'
    },
    // 移动端侧边栏是否打开
    mobileOpen: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 当前激活的主菜单
      activeMenu: this.defaultActiveMenu,
      // 当前激活的子菜单
      activeSubMenu: this.defaultActiveSubMenu,
      // 菜单展开状态
      menuExpanded: {
        modelManagement: this.defaultActiveMenu === 'modelManagement',
        inference: this.defaultActiveMenu === 'inference',
        api: false, // API 接口没有子菜单
        dataProcessing: this.defaultActiveMenu === 'dataProcessing'
      },
      // 菜单路由映射
      menuRoutes: {
        modelManagement: {
          modelLifecycle: '/model/lifecycle',
          modelPerformance: '/model/performance',
          modelConversion: '/model/conversion'
        },
        inference: {
          inferenceHome: '/inference/home',
          createInference: '/inference/create',
          pipelineBuild: '/inference/pipeline',
          batchInference: '/inference/batch',
          inferenceOptimization: '/inference/optimization'
        },
        api: '/api',
        dataProcessing: {
          dataTemplate: '/data/template',
          dataPreprocess: '/data/preprocess',
          dataAugmentation: '/data/augmentation',
          processedResults: '/data/results'
        }
      }
    }
  },
  methods: {
    // 切换菜单展开/收起状态
    toggleMenu(menuName) {
      // 如果点击的是已激活的菜单，只切换展开状态
      if (this.activeMenu === menuName) {
        this.menuExpanded[menuName] = !this.menuExpanded[menuName]
      } else {
        // 如果点击的是其他菜单，激活并切换当前菜单的展开状态
        this.activeMenu = menuName
        this.menuExpanded[menuName] = !this.menuExpanded[menuName]
      }

      // 触发菜单切换事件
      this.$emit('menu-change', {
        menu: menuName,
        expanded: this.menuExpanded[menuName]
      })
    },

    //选择主菜单（无子菜单的菜单项）
    selectMenu(menuName) {
      // 收起所有菜单
      Object.keys(this.menuExpanded).forEach(key => {
        this.menuExpanded[key] = false
      })

      // 激活当前菜单
      this.activeMenu = menuName
      this.activeSubMenu = ''

      // 触发菜单切换事件
      this.$emit('menu-change', {
        menu: menuName,
        subMenu: null,
        route: this.menuRoutes[menuName]
      })

      // 如果在移动端，关闭侧边栏
      this.closeMobileSidebar()
    },

    //选择子菜单
    selectSubMenu(menuName, subMenuName) {
      // 展开当前菜单（如果尚未展开）
      if (!this.menuExpanded[menuName]) {
        this.menuExpanded[menuName] = true
      }

      // 激活主菜单和子菜单
      this.activeMenu = menuName
      this.activeSubMenu = subMenuName

      // 获取路由
      const route = this.menuRoutes[menuName][subMenuName]

      // 触发子菜单切换事件
      this.$emit('submenu-change', {
        menu: menuName,
        subMenu: subMenuName,
        route: route
      })

      // 如果在移动端，关闭侧边栏
      this.closeMobileSidebar()
    },
    //判断子菜单是否激活
    isActiveSubMenu(menuName, subMenuName) {
      return this.activeMenu === menuName && this.activeSubMenu === subMenuName
    },

    //关闭移动端侧边栏
    closeMobileSidebar() {
      if (window.innerWidth <= 768) {
        this.$emit('mobile-close')
      }
    },

    //根据路由设置激活状态
    setActiveByRoute(route) {
      // 遍历菜单路由映射，找到匹配的菜单
      for (const [menuName, menuRoute] of Object.entries(this.menuRoutes)) {
        if (typeof menuRoute === 'string') {
          // 无子菜单的菜单项
          if (menuRoute === route) {
            this.selectMenu(menuName)
            return
          }
        } else {
          // 有子菜单的菜单项
          for (const [subMenuName, subRoute] of Object.entries(menuRoute)) {
            if (subRoute === route) {
              this.activeMenu = menuName
              this.activeSubMenu = subMenuName
              this.menuExpanded[menuName] = true
              return
            }
          }
        }
      }
    }
  },

  mounted() {
    // 如果使用 Vue Router，可以根据当前路由自动设置激活状态
    if (this.$route && this.$route.path) {
      this.setActiveByRoute(this.$route.path)
    }
  },

  watch: {
    // 监听路由变化
    '$route.path'(newPath) {
      if (newPath) {
        this.setActiveByRoute(newPath)
      }
    }
  }
}
</script>

<style scoped>
/* ===== 左侧菜单栏样式 ===== */

/* Remix Icon 图标修复 */
:where([class^="ri-"])::before {
  content: "\f3c2";
}

/* Sidebar 主容器 */
.app-sidebar {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  width: 16rem;
  /* 256px */
  background-color: #ffffff;
  border-right: 1px solid #e5e7eb;
  z-index: 20;
  overflow-y: auto;
}

/* 滚动条样式 */
.app-sidebar::-webkit-scrollbar {
  width: 6px;
}

.app-sidebar::-webkit-scrollbar-track {
  background: transparent;
}

.app-sidebar::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.app-sidebar::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* ===== Logo 区域 ===== */

.sidebar-logo {
  padding: 1.5rem;
}

.sidebar-logo-text {
  font-size: 1.5rem;
  font-family: 'Pacifico', cursive;
  color: #3b82f6;
  margin: 0;
  cursor: pointer;
  transition: opacity 0.2s ease;
  user-select: none;
}

.sidebar-logo-text:hover {
  opacity: 0.8;
}

/* ===== 导航菜单 ===== */

.sidebar-nav {
  margin-top: 0.5rem;
}

.sidebar-nav-container {
  padding: 0.5rem 0.75rem;
}

.sidebar-menu {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

/* 菜单按钮（默认状态） */
.sidebar-menu-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  background-color: transparent;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
}

.sidebar-menu-btn:hover {
  background-color: #f9fafb;
  color: #111827;
}

/* 菜单按钮（激活状态） */
.sidebar-menu-btn.active {
  color: #3b82f6;
  background-color: #eff6ff;
}

/* 菜单按钮内容 */
.sidebar-menu-btn-content {
  display: flex;
  align-items: center;
}

.sidebar-menu-btn-icon {
  margin-right: 0.75rem;
  font-size: 1rem;
}

.sidebar-menu-btn-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sidebar-menu-btn-arrow {
  font-size: 1rem;
  transition: transform 0.2s ease;
  flex-shrink: 0;
}

.sidebar-menu-btn-arrow.expanded {
  transform: rotate(180deg);
}

/* ===== 子菜单 ===== */

/* 子菜单容器 */
.sidebar-submenu {
  margin-top: 0.25rem;
  padding-left: 2.5rem;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

/* 子菜单项 */
.sidebar-submenu-link {
  display: block;
  padding: 0.5rem 0.75rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  text-decoration: none;
  border-radius: 12px;
  transition: all 0.2s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sidebar-submenu-link:hover {
  color: #111827;
  background-color: #f9fafb;
}

.sidebar-submenu-link.active {
  color: #3b82f6;
  background-color: #eff6ff;
}

/* ===== 子菜单动画 ===== */

.submenu-enter-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.submenu-leave-active {
  transition: all 0.2s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  overflow: hidden;
}

.submenu-enter-from,
.submenu-leave-to {
  max-height: 0;
  opacity: 0;
}

.submenu-enter-to,
.submenu-leave-from {
  max-height: 500px;
  opacity: 1;
}

/* ===== 响应式设计 ===== */

/* 平板 */
@media (max-width: 1024px) and (min-width: 769px) {
  .app-sidebar {
    width: 12rem;
    /* 192px */
  }

  .sidebar-logo {
    padding: 1rem;
  }

  .sidebar-logo-text {
    font-size: 1.25rem;
  }

  .sidebar-menu-btn {
    font-size: 0.8125rem;
    padding: 0.4rem 0.6rem;
  }

  .sidebar-submenu {
    padding-left: 2rem;
  }

  .sidebar-submenu-link {
    font-size: 0.8125rem;
    padding: 0.4rem 0.6rem;
  }
}

/* 移动端 */
@media (max-width: 768px) {
  .app-sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  /* 侧边栏打开状态 */
  .app-sidebar.mobile-open {
    transform: translateX(0);
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  }
}

/* ===== 打印样式 ===== */

@media print {
  .app-sidebar {
    display: none;
  }
}
</style>